/**
 * 用户设备管理模块
 * 支持国际化的新架构
 */
const {
	userDeviceCollection,
	patternCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')
const {
	getUserId
} = require('../../common/utils')

// 导入 Redis 或设备状态缓存模块（如果使用Redis）
// 如果使用内存缓存，需要一个全局的设备状态管理器
let deviceStatusCache = null;

// 初始化设备状态缓存
const initDeviceStatusCache = () => {
	if (!deviceStatusCache) {
		// 这里可以连接到Redis或使用内存缓存
		// 示例：使用简单的内存Map
		deviceStatusCache = new Map();
	}
	return deviceStatusCache;
}

// 从缓存获取设备在线状态
const getDeviceOnlineStatus = (sn) => {
	const cache = initDeviceStatusCache();
	const status = cache.get(sn?.toLowerCase());
	
	if (status && status.heartbeat) {
		return status.heartbeat.online === true ? 1 : 0;
	}
	
	// 默认返回离线
	return 0;
}

// 共享的设备权限检查函数
const checkDevicePermission = async (deviceId, userId, context) => {
	// 支持通过_id或device_id查询设备
	const query = {
		$or: [
			{ _id: deviceId },
			{ device_id: deviceId }
		]
	}
	
	const deviceResult = await userDeviceCollection.where(
		dbCmd.and([
			query,
			dbCmd.or([
				{owner_id: userId},
				{shared_users: dbCmd.in([userId])}
			])
		])
	).get()
	
	if (deviceResult.data.length === 0) {
		throw {
			errCode: ERROR.DEVICE_NOT_FOUND,
			errMsg: context.t ? context.t('device.not.found') : '设备不存在或无权限'
		}
	}
	
	return deviceResult.data[0]
}

// 控制设备电源
const controlPower = async (deviceId, data, context) => {
	if (typeof data.power !== 'boolean') {
		throw {
			errCode: ERROR.PARAM_ERROR,
			errMsg: context.t ? context.t('device.power.invalid') : '电源状态参数无效'
		}
	}

	await userDeviceCollection.doc(deviceId).update({
		device_status: data.power ? 1 : 0,
		update_time: new Date()
	})
}

// 控制设备播放图案
const controlPattern = async (deviceId, data, context) => {
	if (!data.pattern_id) {
		throw {
			errCode: ERROR.PARAM_REQUIRED,
			errMsgValue: { param: 'pattern_id' }
		}
	}

	// 验证图案是否存在
	const patternResult = await patternCollection.doc(data.pattern_id).get()
	if (patternResult.data.length === 0) {
		throw {
			errCode: 'PATTERN_NOT_FOUND',
			errMsg: context.t ? context.t('device.pattern.not-found') : '图案不存在'
		}
	}

	const pattern = patternResult.data[0]
	await userDeviceCollection.doc(deviceId).update({
		current_pattern: {
			pattern_id: data.pattern_id,
			pattern_name: pattern.pattern_name,
			progress: 0,
			status: 1 // 播放状态
		},
		update_time: new Date()
	})
}

// 控制设备亮度
const controlBrightness = async (deviceId, data, context) => {
	const brightness = parseInt(data.brightness)
	if (isNaN(brightness) || brightness < 1 || brightness > 100) {
		throw {
			errCode: 'INVALID_BRIGHTNESS',
			errMsg: context.t ? context.t('device.brightness.invalid') : '亮度值必须在1-100之间'
		}
	}

	// 获取设备当前信息
	const deviceResult = await userDeviceCollection.doc(deviceId).get()
	if (!deviceResult.data.length) {
		throw {
			errCode: ERROR.DEVICE_NOT_FOUND,
			errMsg: context.t ? context.t('device.not.found') : '设备不存在'
		}
	}

	const device = deviceResult.data[0]
	let lightSettings = device.light_settings || {}
	lightSettings.brightness = brightness

	await userDeviceCollection.doc(deviceId).update({
		light_settings: lightSettings,
		update_time: new Date()
	})
}

// 控制设备色温
const controlColorTemperature = async (deviceId, data, context) => {
	const colorTemp = parseInt(data.color_temperature)
	if (isNaN(colorTemp) || colorTemp < 2000 || colorTemp > 6500) {
		throw {
			errCode: 'INVALID_COLOR_TEMP',
			errMsg: context.t ? context.t('device.color-temp.invalid') : '色温值必须在2000-6500之间'
		}
	}

	// 获取设备当前信息
	const deviceResult = await userDeviceCollection.doc(deviceId).get()
	if (!deviceResult.data.length) {
		throw {
			errCode: ERROR.DEVICE_NOT_FOUND,
			errMsg: context.t ? context.t('device.not.found') : '设备不存在'
		}
	}

	const device = deviceResult.data[0]
	let lightSettings = device.light_settings || {}
	lightSettings.color_temperature = colorTemp

	await userDeviceCollection.doc(deviceId).update({
		light_settings: lightSettings,
		update_time: new Date()
	})
}

// 控制设备灯光
const controlLighting = async (deviceId, data, context) => {
	if (typeof data.enabled !== 'boolean') {
		throw {
			errCode: ERROR.PARAM_ERROR,
			errMsg: context.t ? context.t('device.lighting.enabled.invalid') : '灯光开关状态参数无效'
		}
	}

	// 获取设备当前信息
	const deviceResult = await userDeviceCollection.doc(deviceId).get()
	if (!deviceResult.data.length) {
		throw {
			errCode: ERROR.DEVICE_NOT_FOUND,
			errMsg: context.t ? context.t('device.not.found') : '设备不存在'
		}
	}

	const device = deviceResult.data[0]
	let lightSettings = device.light_settings || {}

	// 如果启用灯光，验证并设置其他参数
	if (data.enabled) {
		lightSettings.enabled = true
		
		// 验证模式
		if (data.mode) {
			const validModes = ['constant', 'breathing', 'rainbow', 'tracking']
			if (!validModes.includes(data.mode)) {
				throw {
					errCode: 'INVALID_LIGHTING_MODE',
					errMsg: context.t ? context.t('device.lighting.mode.invalid') : '无效的灯光模式'
				}
			}
			lightSettings.mode = data.mode
		}

		// 验证颜色值
		if (data.color) {
			const colorRegex = /^#[0-9A-Fa-f]{6}$/
			if (!colorRegex.test(data.color)) {
				throw {
					errCode: 'INVALID_COLOR',
					errMsg: context.t ? context.t('device.lighting.color.invalid') : '无效的颜色值'
				}
			}
			lightSettings.color = data.color
		}

		// 验证亮度
		if (data.brightness !== undefined) {
			const brightness = parseInt(data.brightness)
			if (isNaN(brightness) || brightness < 0 || brightness > 100) {
				throw {
					errCode: 'INVALID_BRIGHTNESS',
					errMsg: context.t ? context.t('device.lighting.brightness.invalid') : '亮度值必须在0-100之间'
				}
			}
			lightSettings.brightness = brightness
		}

		// 验证变化速度
		if (data.speed !== undefined) {
			const speed = parseInt(data.speed)
			if (isNaN(speed) || speed < 0 || speed > 100) {
				throw {
					errCode: 'INVALID_SPEED',
					errMsg: context.t ? context.t('device.lighting.speed.invalid') : '变化速度必须在0-100之间'
				}
			}
			lightSettings.speed = speed
		}
	} else {
		// 关闭灯光
		lightSettings.enabled = false
	}

	// 更新设备
	await userDeviceCollection.doc(deviceId).update({
		light_settings: lightSettings,
		update_time: new Date()
	})
}

// 控制设备播放设置
const controlPlaybackSettings = async (deviceId, data, context) => {
	// 获取设备当前信息
	const deviceResult = await userDeviceCollection.doc(deviceId).get()
	if (!deviceResult.data.length) {
		throw {
			errCode: ERROR.DEVICE_NOT_FOUND,
			errMsg: context.t ? context.t('device.not.found') : '设备不存在'
		}
	}

	const device = deviceResult.data[0]
	let playbackSettings = device.playback_settings || {}

	// 验证并设置播放速度
	if (data.speed !== undefined) {
		const speed = parseInt(data.speed)
		if (isNaN(speed) || speed < 50 || speed > 200) {
			throw {
				errCode: 'INVALID_PLAYBACK_SPEED',
				errMsg: context.t ? context.t('device.playback.speed.invalid') : '播放速度必须在50-200之间'
			}
		}
		playbackSettings.speed = speed
	}

	// 设置播放完成后暂停
	if (data.pause_after_complete !== undefined) {
		if (typeof data.pause_after_complete !== 'boolean') {
			throw {
				errCode: 'INVALID_PAUSE_SETTING',
				errMsg: context.t ? context.t('device.playback.pause.invalid') : '播放完成后暂停设置无效'
			}
		}
		playbackSettings.pause_after_complete = data.pause_after_complete
	}

	// 验证并设置暂停时长
	if (data.pause_duration !== undefined) {
		const duration = parseInt(data.pause_duration)
		if (isNaN(duration) || duration < 1 || duration > 600) {
			throw {
				errCode: 'INVALID_PAUSE_DURATION',
				errMsg: context.t ? context.t('device.playback.duration.invalid') : '暂停时长必须在1-600秒之间'
			}
		}
		playbackSettings.pause_duration = duration
	}

	// 设置开始新图案前清空沙盘
	if (data.clear_before_new !== undefined) {
		if (typeof data.clear_before_new !== 'boolean') {
			throw {
				errCode: 'INVALID_CLEAR_SETTING',
				errMsg: context.t ? context.t('device.playback.clear.invalid') : '开始新图案前清空设置无效'
			}
		}
		playbackSettings.clear_before_new = data.clear_before_new
	}

	// 更新设备播放设置
	await userDeviceCollection.doc(deviceId).update({
		playback_settings: playbackSettings,
		update_time: new Date()
	})
}

// 获取设备播放列表
const getDevicePlaylist = async (deviceId, context) => {
	const playlistResult = await uniCloud.database().collection('sh_user_playlist').where({
		device_id: deviceId
	}).get()

	if (playlistResult.data.length === 0) {
		throw {
			errCode: 'PLAYLIST_NOT_FOUND',
			errMsg: context.t ? context.t('device.playlist.not-found') : '播放列表不存在'
		}
	}

	return playlistResult.data[0]
}

// 播放指定图案
const playSpecificPattern = async (deviceId, patternId, playlist, context, patternIndex) => {
	// 获取图案信息
	const patternResult = await patternCollection.doc(patternId).get()
	if (patternResult.data.length === 0) {
		throw {
			errCode: 'PATTERN_NOT_FOUND',
			errMsg: context.t ? context.t('device.pattern.not-found') : '图案不存在'
		}
	}

	const pattern = patternResult.data[0]
	const promises = []

	// 更新设备当前播放图案
	promises.push(userDeviceCollection.doc(deviceId).update({
		current_pattern: {
			pattern_id: patternId,
			pattern_name: pattern.pattern_name,
			progress: 0,
			status: 1 // 播放状态
		},
		update_time: new Date()
	}))

	// 更新播放列表状态
	if (playlist && playlist.patterns) {
		const updatedPatterns = playlist.patterns.map(p => ({
			...p,
			is_playing: p.pattern_id === patternId
		}))
		
		const playlistUpdate = {
			patterns: updatedPatterns,
			update_time: new Date()
		}
		
		// 如果指定了索引，更新当前播放索引
		if (patternIndex !== undefined) {
			playlistUpdate.current_index = patternIndex
		} else {
			// 查找图案在播放列表中的索引
			const foundIndex = playlist.patterns.findIndex(p => p.pattern_id === patternId)
			if (foundIndex !== -1) {
				playlistUpdate.current_index = foundIndex
			}
		}
		
		promises.push(uniCloud.database().collection('sh_user_playlist').doc(playlist._id).update(playlistUpdate))
	}

	await Promise.all(promises)
}

// 控制播放
const controlPlay = async (deviceId, device, data, context) => {
	const playlist = await getDevicePlaylist(deviceId, context)
	
	if (data.pattern_id) {
		// 播放指定图案
		await playSpecificPattern(deviceId, data.pattern_id, playlist, context)
	} else if (device.current_pattern && device.current_pattern.pattern_id) {
		// 继续播放当前图案
		await userDeviceCollection.doc(deviceId).update({
			'current_pattern.status': 1,
			update_time: new Date()
		})
	} else if (playlist.patterns && playlist.patterns.length > 0) {
		// 播放播放列表中的第一个图案
		const firstPattern = playlist.patterns[0]
		await playSpecificPattern(deviceId, firstPattern.pattern_id, playlist, context)
	} else {
		throw {
			errCode: 'NO_PATTERN_TO_PLAY',
			errMsg: context.t ? context.t('device.no.pattern') : '没有可播放的图案'
		}
	}
}

// 控制暂停
const controlPause = async (deviceId, device, context) => {
	if (!device.current_pattern || !device.current_pattern.pattern_id) {
		throw {
			errCode: 'NO_PLAYING_PATTERN',
			errMsg: context.t ? context.t('device.no.playing') : '当前没有播放的图案'
		}
	}

	await userDeviceCollection.doc(deviceId).update({
		'current_pattern.status': 2, // 暂停状态
		update_time: new Date()
	})
}

// 控制停止
const controlStop = async (deviceId, device, context) => {
	await userDeviceCollection.doc(deviceId).update({
		current_pattern: {
			pattern_id: '',
			pattern_name: '',
			progress: 0,
			status: 0 // 停止状态
		},
		update_time: new Date()
	})

	// 清除播放列表中的播放状态
	const playlist = await getDevicePlaylist(deviceId, context)
	if (playlist && playlist.patterns) {
		const updatedPatterns = playlist.patterns.map(p => ({
			...p,
			is_playing: false
		}))
		
		await uniCloud.database().collection('sh_user_playlist').doc(playlist._id).update({
			patterns: updatedPatterns,
			update_time: new Date()
		})
	}
}

// 控制下一首
const controlNext = async (deviceId, device, context) => {
	const playlist = await getDevicePlaylist(deviceId, context)
	
	if (!playlist || !playlist.patterns || playlist.patterns.length === 0) {
		throw {
			errCode: 'EMPTY_PLAYLIST',
			errMsg: context.t ? context.t('device.playlist.empty') : '播放列表为空'
		}
	}

	const nextIndex = (playlist.current_index + 1) % playlist.patterns.length
	const nextPattern = playlist.patterns[nextIndex]
	
	await playSpecificPattern(deviceId, nextPattern.pattern_id, playlist, context, nextIndex)
}

// 控制上一首
const controlPrev = async (deviceId, device, context) => {
	const playlist = await getDevicePlaylist(deviceId, context)
	
	if (!playlist || !playlist.patterns || playlist.patterns.length === 0) {
		throw {
			errCode: 'EMPTY_PLAYLIST',
			errMsg: context.t ? context.t('device.playlist.empty') : '播放列表为空'
		}
	}

	const prevIndex = playlist.current_index > 0 ? playlist.current_index - 1 : playlist.patterns.length - 1
	const prevPattern = playlist.patterns[prevIndex]
	
	await playSpecificPattern(deviceId, prevPattern.pattern_id, playlist, context, prevIndex)
}

// 控制播放列表
const controlPlaylist = async (deviceId, data, context) => {
	if (!Array.isArray(data.patterns)) {
		throw {
			errCode: ERROR.PARAM_ERROR,
			errMsg: context.t ? context.t('device.playlist.invalid') : '播放列表格式无效'
		}
	}

	// 验证播放列表中的图案是否存在
	if (data.patterns.length > 0) {
		const patternIds = data.patterns.map(p => p.pattern_id).filter(Boolean)
		if (patternIds.length > 0) {
			const patternResult = await patternCollection.where({
				_id: dbCmd.in(patternIds)
			}).get()
			
			if (patternResult.data.length !== patternIds.length) {
				throw {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: context.t ? context.t('device.playlist.pattern.invalid') : '播放列表中包含无效图案'
				}
			}
		}
	}

	// 更新播放列表
	await uniCloud.database().collection('sh_user_playlist').where({
		device_id: deviceId
	}).update({
		patterns: data.patterns,
		current_index: data.current_index || 0,
		play_mode: data.play_mode || 0,
		auto_play: data.auto_play !== undefined ? data.auto_play : true,
		update_time: new Date()
	})
}

module.exports = {
	/**
	 * 获取用户设备列表
	 * @returns {object} 设备列表
	 */
	async getDeviceList() {
		try {
			const userId = await getUserId(this)
			
			// 获取拥有的设备和被分享的设备
			const deviceResult = await userDeviceCollection.where(
				dbCmd.or([
					{owner_id: userId},
					{shared_users: dbCmd.in([userId])}
				])
			).orderBy('create_time', 'desc').get()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 转换数据格式 - device_name 不再需要多语言处理
			// 不再返回 device_status，由客户端从MQTT缓存中获取实时状态
			const transformedData = transformMultiLangData(deviceResult.data, language, {
				multiLangFields: [],
				keepFields: [
					'device_id', 'device_type', 'device_name', 'sn', 'owner_id', 'shared_users',
					'location', 'light_settings', 'current_pattern', 'last_online_time',
					'create_time', 'update_time'
				],
				idMapping: { '_id': 'id' }
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.list.success') : '获取成功',
				data: transformedData
			}
		} catch (error) {
			console.error('[sh_user_device] getDeviceList error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.list.failed') : '获取设备列表失败'
			}
		}
	},

	/**
	 * 添加设备
	 * @param {object} params 设备参数
	 * @param {string} params.deviceId 设备ID
	 * @param {string} params.sn 设备SN码
	 * @param {string} params.firmwareVersion 固件版本
	 * @param {string} params.hardwareVersion 硬件版本
	 * @param {string} params.macAddress MAC地址
	 * @param {string} params.deviceName 设备名称（字符串）
	 * @param {string} [params.deviceType='pro'] 设备类型
	 * @param {string} [params.location=''] 设备位置
	 * @returns {object} 添加结果
	 */
	async addDevice(params = {}) {
		const {
			deviceId,
			sn,
			firmwareVersion,
			hardwareVersion,
			macAddress,
			deviceName,
			deviceType = 'pro',
			location = ''
		} = params

		if (!deviceId || !sn || !firmwareVersion || !hardwareVersion || !macAddress || !deviceName) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, sn, firmwareVersion, hardwareVersion, macAddress, deviceName' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 检查设备 ID 是否已被绑定
			const existDeviceById = await userDeviceCollection.where({
				device_id: deviceId
			}).get()

			if (existDeviceById.data.length > 0) {
				throw {
					errCode: 'DEVICE_EXISTS',
					errMsg: this.t ? this.t('device.exists') : '设备已被绑定'
				}
			}
			
			// 检查设备 SN 是否已被注册
			const existDeviceBySn = await userDeviceCollection.where({
				sn: sn
			}).get()

			if (existDeviceBySn.data.length > 0) {
				const existingDevice = existDeviceBySn.data[0]
				// 检查是否是当前用户的设备
				if (existingDevice.owner_id === userId) {
					throw {
						errCode: 'DEVICE_ALREADY_OWNED',
						errMsg: this.t ? this.t('device.already.owned') : '您已拥有该设备，无需重复添加'
					}
				} else {
					throw {
						errCode: 'DEVICE_SN_EXISTS',
						errMsg: this.t ? this.t('device.sn.exists') : '该设备已被其他用户绑定'
					}
				}
			}

			// 引用设备模块，确保设备基础信息存在
			const shDevice = require('../sh_device')
			
			// 处理设备名称 - 使用简单字符串格式
			const processedDeviceName = typeof deviceName === 'string' ? deviceName : (deviceName['zh-Hans'] || deviceName['en'] || Object.values(deviceName)[0] || 'Unknown Device')

			// 确保设备基础信息存在于 sh_device 表中
			await shDevice.ensureDevice.call(this, {
				deviceId,
				sn,
				firmwareVersion,
				hardwareVersion,
				macAddress,
				deviceType,
				deviceName: processedDeviceName
			})

			// 添加用户设备关联
			const deviceResult = await userDeviceCollection.add({
				device_id: deviceId,
				device_name: processedDeviceName,
				device_type: deviceType,
				sn,
				firmware_version: firmwareVersion,
				hardware_version: hardwareVersion,
				mac_address: macAddress,
				owner_id: userId,
				shared_users: [],
				device_status: 0,
				location,
				light_settings: {
					enabled: true,
					mode: 'constant',
					color: '#FFFFFF',
					brightness: 80,
					speed: 50,
					color_temperature: 4000
				},
				create_time: new Date(),
				update_time: new Date()
			})

			// 为设备创建默认播放列表
			await uniCloud.database().collection('sh_user_playlist').add({
				device_id: deviceResult.id,
				patterns: [],
				current_index: 0,
				play_mode: 0,
				auto_play: true,
				create_time: new Date(),
				update_time: new Date()
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.add.success') : '设备添加成功',
				data: {
					deviceId: deviceResult.id,
					sn,
					firmwareVersion,
					hardwareVersion,
					macAddress
				}
			}
		} catch (error) {
			console.error('[sh_user_device] addDevice error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.add.failed') : '添加设备失败'
			}
		}
	},

	/**
	 * 更新设备信息
	 * @param {object} params 更新参数
	 * @returns {object} 更新结果
	 */
	async updateDevice({ deviceId, deviceInfo }) {
		if (!deviceId || !deviceInfo) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, deviceInfo' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 使用共享的权限检查函数，允许拥有者和分享者都可以修改设备
			const device = await checkDevicePermission(deviceId, userId, this)

			// 过滤允许更新的字段
			const allowedFields = ['device_name', 'location', 'light_settings', 'playback_settings']
			const updateData = {}
			
			allowedFields.forEach(field => {
				if (deviceInfo[field] !== undefined) {
					updateData[field] = deviceInfo[field]
				}
			})
			
			updateData.update_time = new Date()

			await userDeviceCollection.doc(deviceId).update(updateData)

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.update.success') : '设备更新成功'
			}
		} catch (error) {
			console.error('[sh_user_device] updateDevice error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.update.failed') : '更新设备失败'
			}
		}
	},

	/**
	 * 删除设备
	 * @param {string} deviceId 设备ID
	 * @returns {object} 删除结果
	 */
	async deleteDevice({deviceId}) {
		if (!deviceId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 检查设备权限
			const deviceResult = await userDeviceCollection.doc(deviceId).get()
			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND
				}
			}

			const device = deviceResult.data[0]
			if (device.owner_id !== userId) {
				throw {
					errCode: ERROR.PERMISSION_DENIED,
					errMsg: this.t ? this.t('permission-denied') : '无权限操作此设备'
				}
			}

			// 删除设备
			await userDeviceCollection.doc(deviceId).remove()

			// 删除相关播放列表
			await uniCloud.database().collection('sh_user_playlist').where({
				device_id: deviceId
			}).remove()

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.delete.success') : '设备删除成功'
			}
		} catch (error) {
			console.error('[sh_user_device] deleteDevice error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.delete.failed') : '删除设备失败'
			}
		}
	},

	/**
	 * 通过设备SN删除设备
	 * @param {string} sn 设备序列号
	 * @returns {object} 删除结果
	 */
	async deleteDeviceBySn({sn}) {
		if (!sn) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'sn' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 通过SN查找设备
			const deviceResult = await userDeviceCollection.where({
				sn: sn
			}).get()
			
			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND,
					errMsg: this.t ? this.t('device.not.found') : '设备不存在'
				}
			}

			const device = deviceResult.data[0]
			
			// 检查权限
			if (device.owner_id !== userId) {
				throw {
					errCode: ERROR.PERMISSION_DENIED,
					errMsg: this.t ? this.t('permission-denied') : '无权限操作此设备'
				}
			}

			// 删除设备
			await userDeviceCollection.doc(device._id).remove()

			// 删除相关播放列表
			await uniCloud.database().collection('sh_user_playlist').where({
				device_sn: sn
			}).remove()

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.delete.success') : '设备删除成功',
				data: {
					deviceId: device._id,
					sn: sn
				}
			}
		} catch (error) {
			console.error('[sh_user_device] deleteDeviceBySn error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.delete.failed') : '删除设备失败'
			}
		}
	},

	/**
	 * 移除设备分享（分享者退出设备）
	 * @param {string} sn 设备序列号
	 * @returns {object} 移除结果
	 */
	async removeDeviceShare({sn}) {
		if (!sn) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'sn' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 通过SN查找设备
			const deviceResult = await userDeviceCollection.where({
				sn: sn
			}).get()
			
			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND,
					errMsg: this.t ? this.t('device.not.found') : '设备不存在'
				}
			}

			const device = deviceResult.data[0]
			
			// 检查用户是否是分享用户
			if (!device.shared_users || !device.shared_users.includes(userId)) {
				throw {
					errCode: ERROR.PERMISSION_DENIED,
					errMsg: this.t ? this.t('device.not.shared.user') : '您不是该设备的分享用户'
				}
			}

			// 从分享用户列表中移除当前用户
			const newSharedUsers = device.shared_users.filter(id => id !== userId)
			
			await userDeviceCollection.doc(device._id).update({
				shared_users: newSharedUsers
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.share.remove.success') : '已退出设备分享',
				data: {
					deviceId: device._id,
					sn: sn
				}
			}
		} catch (error) {
			console.error('[sh_user_device] removeDeviceShare error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.share.remove.failed') : '退出设备分享失败'
			}
		}
	},



	/**
	 * 控制设备
	 * @param {object} params 控制参数
	 * @param {string} params.deviceId 设备ID (必填)
	 * @param {string} params.action 操作类型 (必填): power|pattern|brightness|color_temperature|lighting|play|pause|stop|next|prev|playlist
	 * @param {object} params.data 操作数据 (必填)
	 * @returns {object} 控制结果
	 */
	async controlDevice({ deviceId, action, data }) {
		if (!deviceId || !action || !data) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, action, data' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 检查设备权限并获取设备信息
			const device = await checkDevicePermission(deviceId, userId, this)
			
			// 根据操作类型调用对应的方法
			switch (action) {
				case 'power':
					await controlPower(deviceId, data, this)
					break
				case 'pattern':
					await controlPattern(deviceId, data, this)
					break
				case 'brightness':
					await controlBrightness(deviceId, data, this)
					break
				case 'color_temperature':
					await controlColorTemperature(deviceId, data, this)
					break
				case 'lighting':
					await controlLighting(deviceId, data, this)
					break
				case 'play':
					await controlPlay(deviceId, device, data, this)
					break
				case 'pause':
					await controlPause(deviceId, device, this)
					break
				case 'stop':
					await controlStop(deviceId, device, this)
					break
				case 'next':
					await controlNext(deviceId, device, this)
					break
				case 'prev':
					await controlPrev(deviceId, device, this)
					break
				case 'playlist':
					await controlPlaylist(deviceId, data, this)
					break
				case 'playback_settings':
					await controlPlaybackSettings(deviceId, data, this)
					break
				default:
					throw {
						errCode: 'INVALID_ACTION',
						errMsg: this.t ? this.t('device.action.invalid') : '无效的操作类型'
					}
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.control.success') : '设备控制成功'
			}
		} catch (error) {
			console.error('[sh_user_device] controlDevice error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.control.failed') : '设备控制失败'
			}
		}
	},

	/**
	 * 获取设备详情
	 * @param {string} deviceId 设备ID (可选，与sn二选一)
	 * @param {string} sn 设备SN码 (可选，与deviceId二选一)
	 * @returns {object} 设备详情
	 */
	async getDeviceDetail({deviceId, sn}) {
		if (!deviceId && !sn) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId or sn' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			// 构建查询条件：支持通过 deviceId 或 sn 查询
			const deviceCondition = deviceId ? {_id: deviceId} : {sn: sn}
			
			// 检查设备权限
			const deviceResult = await userDeviceCollection.where(
				dbCmd.and([
					deviceCondition,
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get()

			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND
				}
			}

			const device = deviceResult.data[0]
			// 使用查询到的实际设备ID（无论通过deviceId还是sn查询）
			const actualDeviceId = device._id

			// 获取播放列表信息
			const playlistResult = await uniCloud.database().collection('sh_user_playlist').where({
				device_id: actualDeviceId
			}).get()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 如果设备有当前播放的图案，获取完整的图案信息
			let currentPatternDetail = null
			if (device.current_pattern && device.current_pattern.pattern_id) {
				const patternResult = await patternCollection.where({
					_id: device.current_pattern.pattern_id,
					status: 1 // 只获取已发布的图案
				}).get()

				if (patternResult.data.length > 0) {
					const pattern = patternResult.data[0]
					
					// 转换图案数据格式
					const transformedPattern = transformMultiLangData([pattern], language, {
						multiLangFields: ['pattern_name', 'description'],
						keepFields: [
							'pattern_file', 'preview_image', 'category', 'tags', 'duration', 'play_time',
							'difficulty', 'download_count', 'favorite_count', 'designer','light_settings',
							'is_featured', 'is_premium', 'compatible_devices', 'create_time'
						],
						idMapping: { '_id': 'pattern_id' }
					})[0]

					// 合并当前播放状态和完整图案信息
					currentPatternDetail = {
						...transformedPattern,
						progress: device.current_pattern.progress || 0,
						status: device.current_pattern.status || 0
					}
				}
			}

			// 转换设备数据格式 - device_name 不再需要多语言处理
			const transformedDevice = transformMultiLangData([device], language, {
				multiLangFields: [], // 移除 device_name 的多语言处理
				keepFields: [
					'device_id', 'device_type', 'device_name', 'sn', 'owner_id', 'shared_users', 'device_status',
					'location', 'last_online_time',
					'playback_settings', 'create_time', 'update_time'
				],
				idMapping: { '_id': 'id' }
			})[0]

			// 添加 is_owner 字段标识当前用户是否为设备拥有者
			transformedDevice.is_owner = device.owner_id === userId

			// 手动添加 light_settings，避免被 transformMultiLangData 处理
			transformedDevice.light_settings = device.light_settings || {
				enabled: true,
				mode: 'constant',
				color: '#FFFFFF',
				brightness: 80,
				speed: 50,
				color_temperature: 4000
			}

			// 添加完整的当前图案信息
			transformedDevice.current_pattern = currentPatternDetail

			// 添加播放列表信息
			let playlist = null
			if (playlistResult.data.length > 0) {
				playlist = playlistResult.data[0]
				
				// 确保每个图案都有播放状态
				if (playlist.patterns && playlist.patterns.length > 0) {
					const currentPatternId = device.current_pattern?.pattern_id || ''
					
					// 更新每个图案的播放状态
					playlist.patterns = playlist.patterns.map(pattern => ({
						...pattern,
						is_playing: pattern.pattern_id === currentPatternId
					}))
				}
			}
			transformedDevice.playlist = playlist

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.detail.success') : '获取成功',
				data: transformedDevice
			}
		} catch (error) {
			console.error('[sh_user_device] getDeviceDetail error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.detail.failed') : '获取设备详情失败'
			}
		}
	},

	/**
	 * 更新设备状态
	 * @param {object} params 更新参数
	 * @returns {object} 更新结果
	 */
	async updateDeviceStatus({deviceId, status, currentPattern}) {
		if (!deviceId || status === undefined) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, status' }
			}
		}

		try {
			const updateData = {
				device_status: status,
				last_online_time: new Date(),
				update_time: new Date()
			}

			if (currentPattern) {
				updateData.current_pattern = currentPattern
			}

			await userDeviceCollection.doc(deviceId).update(updateData)

			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.status.update.success') : '状态更新成功'
			}
		} catch (error) {
			console.error('[sh_user_device] updateDeviceStatus error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.status.update.failed') : '更新设备状态失败'
			}
		}
	},

	/**
	 * 转移设备所有权（重新配置WiFi时调用）
	 * @param {string} sn 设备序列号 (必填)
	 * @returns {object} 转移结果
	 */
	async transferDeviceOwnership({sn}) {
		if (!sn) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'sn' }
			}
		}

		try {
			const userId = await getUserId(this)
			
			console.log('[sh_user_device] 转移设备所有权 - SN:', sn, '新所有者:', userId)
			
			// 查找设备
			const deviceResult = await userDeviceCollection.where({
				sn: sn
			}).get()

			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND,
					errMsg: this.t ? this.t('device.not.found') : '设备不存在'
				}
			}

			const device = deviceResult.data[0]
			const oldOwnerId = device.owner_id
			
			// 如果已经是所有者，无需转移
			if (oldOwnerId === userId) {
				console.log('[sh_user_device] 用户已是设备所有者，无需转移')
				return {
					errCode: 0,
					errMsg: this.t ? this.t('device.already.owner') : '您已是设备所有者',
					data: {
						transferred: false,
						reason: 'already_owner'
					}
				}
			}
			
			// 准备更新数据
			const updateData = {
				owner_id: userId,
				update_time: new Date()
			}
			
			// 如果新所有者在分享列表中，从分享列表移除
			let sharedUsers = device.shared_users || []
			if (sharedUsers.includes(userId)) {
				console.log('[sh_user_device] 新所有者在分享列表中，移除:', userId)
				sharedUsers = sharedUsers.filter(id => id !== userId)
				updateData.shared_users = sharedUsers
			}
			
			// 执行更新
			await userDeviceCollection.doc(device._id).update(updateData)
			
			console.log('[sh_user_device] 设备所有权转移成功 - 从', oldOwnerId, '到', userId)
			
			return {
				errCode: 0,
				errMsg: this.t ? this.t('device.ownership.transferred') : '设备所有权已转移',
				data: {
					transferred: true,
					old_owner_id: oldOwnerId,
					new_owner_id: userId,
					removed_from_shared: sharedUsers !== device.shared_users
				}
			}
		} catch (error) {
			console.error('[sh_user_device] transferDeviceOwnership error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('device.ownership.transfer.failed') : '转移设备所有权失败'
			}
		}
	}
}
